import 'package:flutter/material.dart';
import 'package:httpdio/screens/comments_screen.dart';
import 'package:httpdio/screens/main_navigation_screen.dart';
import 'package:httpdio/screens/posts_screen.dart';
import 'package:provider/provider.dart';
import 'screens/user_screen.dart';
import 'service/user_service.dart';
import 'widgets/error_widget.dart';

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
/*    return MultiProvider(
      providers: [Provider(create: (_) => UserService())],
      child: MaterialApp(
          title: 'Dio高级示例',
          theme: _buildAppTheme(),
          home: UserScreen(),
          debugShowCheckedModeBanner: false,
          onGenerateRoute: _generateRoute,
          builder: (context, child) {
            //全局错误处理
            return GestureDetector(
              onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
              child: MediaQuery(
                data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
                child: child!,
              ),
            );
          }),
    );
  }*/
    return MaterialApp(
      title: '综合应用',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      initialRoute: '/',
      routes: {
        '/': (context) => const MainNavigationScreen(),
        '/posts': (context) => const PostsScreen(),
        '/comments': (context) => const CommentsScreen(),
      },
      onGenerateRoute: (settings) {
        // 处理带参数的动态路由
        if (settings.name == '/user/posts') {
          final args = settings.arguments as Map<String, dynamic>;
          return MaterialPageRoute(
            builder: (context) => PostsScreen(
              userId: args['userId'],
              userName: args['userName'],
            ),
          );
        }

        if (settings.name == '/user/comments') {
          final args = settings.arguments as Map<String, dynamic>;
          return MaterialPageRoute(
            builder: (context) => CommentsScreen(
              userId: args['userId'],
              userName: args['userName'],
            ),
          );
        }

        if (settings.name == '/post/comments') {
          final args = settings.arguments as Map<String, dynamic>;
          return MaterialPageRoute(
            builder: (context) => CommentsScreen(
              postId: args['postId'],
              postTitle: args['postTitle'],
            ),
          );
        }

        return MaterialPageRoute(
          builder: (context) => Scaffold(
            appBar: AppBar(title: const Text('页面不存在')),
            body: const Center(child: Text('找不到该页面')),
          ),
        );
      },
    );
  }
}

// 应用主题配置
ThemeData _buildAppTheme() {
  return ThemeData(
      primarySwatch: Colors.deepOrange,
      visualDensity: VisualDensity.adaptivePlatformDensity,
      scaffoldBackgroundColor: Colors.grey[50],
      appBarTheme: const AppBarTheme(
          elevation: 0,
          centerTitle: true,
          backgroundColor: Colors.white,
          iconTheme: IconThemeData(color: Colors.black),
          titleTextStyle: TextStyle(
              color: Colors.black, fontSize: 20, fontWeight: FontWeight.w600)),
      inputDecorationTheme: InputDecorationTheme(
        border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
        contentPadding:
            const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
      ),
      elevatedButtonTheme: ElevatedButtonThemeData(
        style: ElevatedButton.styleFrom(
            padding: const EdgeInsets.symmetric(vertical: 16),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12))),
      ),
      textTheme: const TextTheme(
        headlineMedium: TextStyle(fontWeight: FontWeight.w600),
        bodyLarge: TextStyle(fontSize: 16),
      ));
}

//路由配置
Route<dynamic>? _generateRoute(RouteSettings settings) {
  switch (settings.name) {
// 可以添加更多路由
    // case '/details':
    //   return MaterialPageRoute(builder: (_) => DetailsScreen());
    default:
      return MaterialPageRoute(
          builder: (_) => Scaffold(
                appBar: AppBar(
                  title: const Text('页面不存在'),
                ),
                body: const Center(child: Text('找不到该页面')),
              ));
  }
}

// 全局加载指示器
class GlobalLoadingIndicator extends StatelessWidget {
  const GlobalLoadingIndicator({super.key});

  @override
  Widget build(BuildContext context) {
    return const Center(
      child: CircularProgressIndicator(),
    );
  }
}

// 全局错误处理页面
class GlobalErrorPage extends StatelessWidget {
  final String message;
  final VoidCallback onRetry;

  const GlobalErrorPage(
      {super.key, required this.message, required this.onRetry});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomErrorWidget(
        message: message,
        onRetry: onRetry,
      ),
    );
  }
}
